﻿using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using System.Xml.Linq;

namespace SunwellLauncher
{
    /// <summary>
    /// Interaction logic for AddWindow.xaml
    /// </summary>
    public partial class AddWindow : Window
    {
        private Realmlists realmlists;
        private FrameworkElement fe;
        private FileSystemWatcher watcher;
        private XDocument doc;
        private MainWindow mw;

        public AddWindow(Realmlists rl, XDocument xd)
        {
            InitializeComponent();

            mw = new MainWindow();
            doc = xd; //mw.LoadXML();

            realmlists = rl;
        }

        #region Events

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            //CreateWatcher();

            XElement newRealm = new XElement("Realm",
                                             new XElement("name", txtbName.Text),
                                             new XElement("address", txtbAddress.Text),
                                             new XElement("website", txtbSite.Text));

            XElement xElement = doc.Element("Realmlists");
            if (xElement != null) xElement.Add(newRealm);
            doc.Save(mw.path + "/Realmlists.xml");

            realmlists.Realm.Add(new Realm() { Name = txtbName.Text, Address = txtbAddress.Text, Website = txtbSite.Text });

            this.Close();
        }
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            fe = (FrameworkElement)this.Template.FindName("MainWin", this);
            if (null != fe)
            {
                fe.MouseLeftButtonDown += new MouseButtonEventHandler(Window_MouseLeftButtonDown);
            }
        }
        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        } 
        #endregion
        #region Methods

        private void CreateWatcher()
        {
            watcher = new FileSystemWatcher();
            watcher.Filter = "Realmlists.xml";
            watcher.Changed += watcher_FileChanged;
            watcher.Path = mw.path;
            watcher.EnableRaisingEvents = true;
        }
        void watcher_FileChanged(object sender, FileSystemEventArgs e)
        {
            Dispatcher.Invoke(DispatcherPriority.Normal, new MainWindow.ListItemsAdd(mw.ListItemsAddFromXML), doc);

            watcher.EnableRaisingEvents = false;
            watcher.Created -= watcher_FileChanged;
            watcher.Dispose();
        }
        #endregion
    }
}
